<template>
  <div class="box">
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/welcome' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>添加商品</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图区域 -->
    <el-card>
      <!-- 顶部警告框 -->
      <el-alert
        title="添加商品信息"
        type="info"
        effect="dark"
        show-icon
        center
        :closable="false"
      >
      </el-alert>
      <!-- 步骤条区域 -->

      <el-steps
        :space="300"
        :active="activeIndex - 0"
        finish-status="success"
        align-center
      >
        <el-step title="基本信息"></el-step>
        <el-step title="商品参数"></el-step>
        <el-step title="商品属性"></el-step>
        <el-step title="商品图片"></el-step>
        <el-step title="商品内容"></el-step>
        <el-step title="完成"></el-step>
      </el-steps>

      <!-- 侧边tab栏区域 -->
      <template>
        <el-form
          :model="addForm"
          :rules="addFormRules"
          ref="addFormRef"
          label-width="100px"
          label-position="top"
        >
          <el-tabs
            tab-position="left"
            v-model="activeIndex"
            :before-leave="beforeTagsLeave"
            @tab-click="tabClicked"
          >
            <!-- 基本信息栏 -->
            <el-tab-pane label="基本信息" name="0">
              <el-form-item label="商品名称" prop="goods_name">
                <el-input v-model="addForm.goods_name"></el-input>
              </el-form-item>
              <el-form-item label="商品价格" prop="goods_price">
                <el-input
                  v-model="addForm.goods_price"
                  type="number"
                ></el-input>
              </el-form-item>
              <el-form-item label="商品重量" prop="goods_weight">
                <el-input v-model="addForm.goods_weight"></el-input>
              </el-form-item>
              <el-form-item label="商品数量" prop="goods_number">
                <el-input
                  v-model="addForm.goods_number"
                  type="number"
                ></el-input>
              </el-form-item>
              <el-form-item label="商品分类" prop="goods_cat">
                <!-- 级联选择器栏 -->
                <el-cascader
                  v-model="addForm.goods_cat"
                  :options="typeList"
                  :props="typeProps"
                  @change="handleChange"
                ></el-cascader>
              </el-form-item>
            </el-tab-pane>
            <!-- 商品参数页面 -->
            <el-tab-pane label="商品参数" name="1">
              <!-- 渲染表单的item项 -->
              <el-form-item
                v-for="item in manyTableData"
                :key="item.attr_id"
                :label="item.attr_name"
              >
                <!-- 渲染复选框 -->
                <template>
                  <el-checkbox-group v-model="item.attr_vals">
                    <el-checkbox
                      :label="checkItem"
                      v-for="(checkItem, index) in item.attr_vals"
                      :key="index"
                      border
                      size="mini"
                    ></el-checkbox>
                  </el-checkbox-group>
                </template>
              </el-form-item>
            </el-tab-pane>
            <!-- 商品属性页面 -->
            <el-tab-pane label="商品属性" name="2">
              <!-- 渲染item表单项 -->
              <el-form-item
                v-for="item in onlyTableData"
                :key="item.attr_id"
                :label="item.attr_name"
              >
                <el-input
                  v-model="item.attr_vals"
                  placeholder="请输入内容"
                ></el-input>
              </el-form-item>
            </el-tab-pane>
            <!-- 上传图片页面 -->
            <el-tab-pane label="商品图片" name="3">
              <!-- action表示图片要上传到后台的地址 -->
              <el-upload
                action="http://127.0.0.1:8888/api/private/v1/upload"
                :on-preview="handlePreview"
                :on-remove="handlePicRemove"
                list-type="picture"
                :headers="headerObj"
                :on-success="handleSuccess"
              >
                <el-button size="small" type="primary">点击上传</el-button>
              </el-upload></el-tab-pane
            >
            <!-- 商品内容页面 -->
            <el-tab-pane label="商品内容" name="4">
              <!-- 富文本编辑器组件 -->
              <quill-editor v-model="addForm.goods_introduce"></quill-editor>
              <!-- 添加商品按钮 -->
              <el-button type="primary" class="btnAdd" @click="add"
                >添加商品</el-button
              >
            </el-tab-pane>
          </el-tabs>
        </el-form>
      </template>
    </el-card>

    <!-- 图片显示对话框 -->
    <el-dialog title="图片预览" :visible.sync="viewDialogVisible" width="50%">
      <img :src="viewPath" />
    </el-dialog>
  </div>
</template>
<script>
import _ from 'lodash'
export default {
  data () {
    return {
      // 步骤条的初始行为
      activeIndex: '0',
      // 添加表单数据绑定
      addForm: {
        goods_name: '',
        goods_price: 0,
        goods_weight: 0,
        goods_number: 0,
        // 商品所属的分类id构成的数组
        goods_cat: [],
        // 上传图片的临时路径
        pics: [],
        // 商品详情描述
        goods_introduce: '',
        // 动态参数和静态属性
        attrs: []
      },
      // 表单规则设置
      addFormRules: {
        goods_name: [
          { required: true, message: '请输入商品名称', trigger: 'blur' }
        ],
        goods_price: [
          { required: true, message: '请输入商品价格', trigger: 'blur' }
        ],
        goods_weight: [
          { required: true, message: '请输入商品重量', trigger: 'blur' }
        ],
        goods_number: [
          { required: true, message: '请输入商品数量', trigger: 'blur' }
        ],
        goods_cat: [
          { required: true, message: '请输入商品分类', trigger: 'blur' }
        ]
      },
      // 商品分类数据列表
      typeList: [],
      // 商品分类数据配置
      typeProps: {
        expandTrigger: 'hover',
        label: 'cat_name',
        value: 'cat_id',
        children: 'children'
      },
      // 动态参数数据
      manyTableData: [],
      // 静态属性数据
      onlyTableData: [],
      // 复选框绑定数据
      checkList: [],
      // 图片上传组件的headers请求头对象
      headerObj: {
        Authorization: window.sessionStorage.getItem('token')
      },
      // 图片绝对路径
      viewPath: '',
      // 图片预览框的显示与隐藏
      viewDialogVisible: false
    }
  },
  methods: {
    // 获取商品分类数据列表
    async gettypeList () {
      const { data: res } = await this.$http.get('categories')
      if (res.meta.status !== 200) {
        return this.$message.error('获取商品分类数据列表失败！')
      }
      this.typeList = res.data
      console.log(this.typeList)
    },
    // 级联选择器数据变化触发函数
    handleChange () {
      if (this.addForm.goods_cat.length !== 3) {
        this.$message.error('只允许选择三级属性')
        this.addForm.goods_cat = []
      }
      // console.log(this.addForm.goods_cat)
    },
    // 切换标签页前的钩子函数
    beforeTagsLeave (activeName, oldActiveName) {
      if (this.addForm.goods_cat.length !== 3 && oldActiveName === '0') {
        this.$message.error('请先选择商品分类！')
        console.log(activeName, oldActiveName)
        return false
      }
    },
    // tab页切换时触发函数
    async tabClicked () {
      if (this.activeIndex === '1') {
        const { data: res } = await this.$http.get(
          `categories/${this.cateID}/attributes`,
          {
            params: { sel: 'many' }
          }
        )
        res.data.forEach(item => {
          item.attr_vals =
            item.attr_vals.length === 0 ? [] : item.attr_vals.split(' ')
        })
        if (res.meta.status !== 200) {
          return this.$message.error('获取数据失败')
        }
        this.manyTableData = res.data
      } else if (this.activeIndex === '2') {
        const { data: res } = await this.$http.get(
          `categories/${this.cateID}/attributes`,
          {
            params: { sel: 'only' }
          }
        )
        if (res.meta.status !== 200) {
          return this.$message.error('获取数据失败')
        }
        this.onlyTableData = res.data
        console.log(this.onlyTableData)
      }
    },
    // 处理图片预览事件
    handlePreview (file) {
      this.viewPath = file.response.data.url
      this.viewDialogVisible = true
    },
    // 监听图片上传成功的事件
    handleSuccess (response) {
      if (response.meta.status !== 200) {
        return this.$message.error('上传失败')
      }
      // 1.拼接得到一个图片信息对象
      this.$message.success('上传成功')
      const picInfo = { pic: response.data.tmp_path }
      // 2.将图片信息对象push到pics数组中
      this.addForm.pics.push(picInfo)
    },
    // 监听图片移除事件
    handlePicRemove (file) {
      // 根据索引值，调用splice方法移除文件
      const filePath = file.response.data.tmp_path
      // findIndex遍历数组，返回符合x.pci ===filePath的索引值
      const i = this.addForm.pics.forEach((item, index) => {
        if (item.pic === filePath) {
          return index
        }
      })
      // 索引值传入splice移除数据
      this.addForm.pics.splice(i, 1)
      console.log(this.addForm.pics)
    },
    // 提交表单数据
    async add () {
      // 表单预校验
      this.$refs.addFormRef.validate(valid => {
        if (!valid) {
          return this.$message.error('请填写必要的表单项！')
        }
      })
      // 执行添加的业务逻辑
      // lodashi cloneDeep(obj) =>深拷贝addForm
      const addFormClone = _.cloneDeep(this.addForm)
      addFormClone.goods_cat = addFormClone.goods_cat.join(',')
      // 处理动态参数和静态属性
      this.manyTableData.forEach(item => {
        const newInfo = {
          attr_id: item.attr_id,
          attr_value: item.attr_vals.join(',')
        }
        this.addForm.attrs.push(newInfo)
      })
      this.onlyTableData.forEach(item => {
        const newInfo = {
          attr_id: item.attr_id,
          attr_value: item.attr_vals
        }
        this.addForm.attrs.push(newInfo)
      })
      addFormClone.attrs = this.addForm.attrs
      // 发起请求添加商品
      // 商品的名称必须唯一的
      const { data: res } = await this.$http.post('goods', addFormClone)
      console.log(res)
      if (res.meta.status !== 201) {
        return this.$message.error(res.meta.msg)
      }
      this.$message.success('添加商品成功')
      this.$router.push('/goods')
    }
  },
  computed: {
    // 获取ID的计算属性
    cateID () {
      if (this.addForm.goods_cat.length === 3) {
        return this.addForm.goods_cat[2]
      } else {
        return null
      }
    }
  },
  created () {
    this.gettypeList()
  }
}
</script>
<style lang="less" scoped>
.el-card {
  margin-top: 20px;
}
.el-steps {
  margin-top: 25px;
}

/deep/ .el-step__title {
  font-size: 13px;
}

.el-tabs {
  margin-top: 20px;
}

.el-checkbox {
  margin-right: 10px;
}

.btnAdd {
  margin-top: 10px;
}
</style>
